<style type="text/css" title="currentStyle">
	@import "../media/css/demo_page.css";
	@import "../media/css/demo_table_jui.css";
	@import "../examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
	@import "media/css/TableTools_JUI.css";
</style>
<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#onTable, #offTable').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
			"sDom": 'Tlfrtip',
			"oTableTools": {
				"aButtons": [
					"copy", "csv", "xls", "pdf", "print",
					{
						"sExtends":    "collection",
						"sButtonText": "Save",
						"aButtons":    [ "csv", "xls", "pdf" ]
					}
				]
			}
		} );
	} );
</script>
<?php
function chk_folder($filename)
{ //echo $filename;
	$fp_load = @fopen($filename, "rb");
	if ( $fp_load )
	{ 
		return true;
	}
	else
	{ 
		return false;
	}
}


function gpspathFunAll($date_offline,$deviceIMEI)
{
	$path1=DATAPATH.date('d-m-Y',strtotime($date_offline))."/".$deviceIMEI.".txt";
	//$path1 = "http://localhost/src/352848025673738.txt";
	
	if(chk_folder($path1))
	{
		$file1 = @fopen($path1, "r");
		if($file1)
		{
			$i=0;
			while(!feof($file1))
			{
			  $data1= fgets($file1);				 
			}
			$data1 = getSortedData($data1);
			fclose($file1);
		}
		return $data1;
	}
		
}

function sec2hms($sec, $padHours=FALSE) {
    $hours_min_secs = "";
    $hours = INTVAL(INTVAL($sec) / 3600); 
    $hours_min_secs .= ($padHours) ? STR_PAD($hours, 2, "0", STR_PAD_LEFT). ':' : $hours. ':';

    $minutes = INTVAL(($sec / 60) % 60); 
   $hours_min_secs .= STR_PAD($minutes, 2, "0", STR_PAD_LEFT). ':';
    $seconds = INTVAL($sec % 60); 
    $hours_min_secs .= STR_PAD($seconds, 2, "0", STR_PAD_LEFT);
    return $hours_min_secs;
}

function addcolon($input){
  $tmp = '';
 for($i=0;$i<strlen($input);$i+=2){
  $tmp.=substr($input, $i, 2).':';
 }
 $input=substr($tmp, 0, strlen($tmp)-1);

 return $input;
}


function getACReport($data,$st_time,$en_time,$onoff)
{
$cnt = 1;
$tmp=-1;
$t1=0.0;
$t2=0.0;
$timeArr= array();
$timediff=array();
$strTime='';
$endTime='';
$totTime = 0;
$k1 = 0;
$totDist = 0;

$strOffTime = '';
$strOnTime = '';
$endOnTime = '';
$endOffTime = '';

	//$file = DATAPATH.date("d-m-Y", strtotime($sdate))."/".$devId.".txt";
	//exit;
	if(count($data)>0)
	{
	 $data1=explode("#",$data);

	 for($j1=0;$j1<count($data1);$j1++)
	 {
		$data2=explode("@",$data1[$j1]);        

		if(count($data2)>1)
		{
			$data3=explode(",",$data2[1]);
			//echo date("d-m-Y", strtotime($sdate))."==".date("d-m-Y",@mktime(($data3[4]+5),($data3[5]+30),$data3[6],$data3[2],$data3[1],$data3[3]));
			$device = $data3[0];
			$geodate = $data3[8]." ".$data3[9];
			$geoTime = date("H:i:s",strtotime($data3[9]));
			$curTime = explode(":",date("H:i:s",strtotime($data3[9])));
			$curTime = (($curTime[0]) * 60) + $curTime[1];
			
			if($curTime >= $st_time && $curTime<=$en_time)
			{			
				//print_r($data3);	
				//echo "<br><br>";	
				if(!in_array($geoTime,$timeArr))
				{  
					$splitParam = explode(" ",$data3[7]);
					//print_r($splitParam);exit;
					//echo " A ".in_array($onoffState,$splitParam)." = ".$onoff;
					//echo "<br><br>";
					if(in_array($onoff,$splitParam) == 1 && $strTime=='')
					{							
						$strTime = date("H:i:s",strtotime($data3[9]));											
					}
					else if(in_array($onoff,$splitParam)!= 1 && $endTime=='' && $strTime!='')
					{ 
						//$data4=explode("@",$data1[$j1-1]);
						//$data5=explode(",",$data4[1]);
						$endTime = date("H:i:s",strtotime($data3[9]));
						
						$finaTime = $geodate."#".$strTime."#".$endTime."#".gmdate("H:i:s",(strtotime($endTime) - strtotime($strTime)))."#".$device;
						array_push($timediff, $finaTime);											
						$strTime = '';
						$endTime = '';
						$diff = '';
						//exit;
					}
					
					$cnt++; 
					array_push($timeArr,$geoTime);
				}
			}
		}
	}
	
	}
	if(count($timediff) > 0)
		return implode("@",$timediff);
	else 
		return "";
}

if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	


?>
<script type="text/javascript" language="javascript">

/*function days_between(date1, date2) {

    var ONE_DAY = 1000 * 60 * 60 * 24

    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()
	var difference_ms = date1_ms - date2_ms
    return Math.round(difference_ms/ONE_DAY)

}*/
var ajax1=new sack();
function days_between(startDate, endDate)
{
    return endDate - startDate;
}
function showFormDiv()
{
	
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}


function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  { alert("Select Device");  document.getElementById('map_device_id').focus();  return 0;  }
  
  
  if(document.getElementById('rdAlertBy').value== 0 && document.getElementById('map_device_id').value != 0)
  { alert("Please Select Input Parameter");  document.getElementById('rdAlertBy').focus();  return 0;  }
  
  if(document.getElementById('rdAlertBy').value== 0 && document.getElementById('map_device_id').value == 0)
  { alert("Please Select Device first");  document.getElementById('rdAlertBy').focus();  return 0;  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
	var t1=document.getElementById('from_date').value ;
        var t2=document.getElementById('to_date').value;

        var one_day=1000*60*60*24; 
		var x=t1.split("-");     
        var y=t2.split("-");
        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0]);
        var month1=x[1]-1;
        var month2=y[1]-1;
        var diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
         
		 if(diff < 0){
       alert("From Date should be prior to To Date."); document.getElementById('to_date').select();return 0;

		 }

	
	return 1;
	
}
function sendCSVData()
{
  document.frmKiloData.submit();
}
function getDeviceDetails(e)
{
	
	document.frm_map_filter.rdAlertBy.selectedIndex = 0;
	document.frm_map_filter.txtVehicleName.value = e.options[e.selectedIndex].text;
	val = e.options[e.selectedIndex].value.split("_");
	document.frm_map_filter.txtVehicleImei.value = val[1]
	
	ajax1.requestFile = 'ajax_server.php?getAlertListfor='+val[0];			
	ajax1.onCompletion = function(){getAlertList()};
	document.getElementById('rdAlertBy').innerHTML = '</option value=0>Loading...</option>';
	ajax1.runAJAX();
	
}
function getAlertList(type)
{
	var alrtListArr = ajax1.response.split("#");
	var obj = document.getElementById('rdAlertBy');
	
	var selLengh = 0;
	obj.options[0] = new Option("Select Parameter",0);
	selLengh++;
	//removeOptionLast(selLengh)
	for(k=0;k<alrtListArr.length-1;k++)
	{
		var portVal = alrtListArr[k].split("_");
		if(portVal[1] != 0)
		{
			if(type == "_"+portVal[1])
			{
				obj.options[selLengh] = new Option(portVal[0], portVal[0]+"_"+portVal[1]);
				obj.options[selLengh].selected = true;
			}
			else
			{
				obj.options[selLengh] = new Option(portVal[0], portVal[0]+"_"+portVal[1]);
			}
			selLengh++;
		}
		
	}
}
function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{

		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';

}
jQuery(function() {

    //$("#time3, #time4").timePicker();	 onchange="document.frm_map_filter.txtVehicleName.value = this.options[selectedIndex].text"
	 $("#time3, #time4").timePicker({
	  startTime: "12:01 AM", // Using string. Can take string or Date object.
	  endTime: "11:59 PM", // Using Date object here.
	  show24Hours: false,
	  separator: ':',
	  step: 1});    
        
    // Store time used by duration.
    var oldTime = $.timePicker("#time3").getTime();
    
    // Keep the duration between the two inputs.
    $("#time3").change(function() {
      if ($("#time4").val()) { // Only update when second input has a value.
        // Calculate duration.
        var duration = ($.timePicker("#time4").getTime() - oldTime);
        var time = $.timePicker("#time3").getTime();
        // Calculate and update the time in the second input.
        $.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
        oldTime = time;
      }
    });
    // Validate.
    $("#time4").change(function() {
      if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
        $(this).addClass("error");
      }
      else {
        $(this).removeClass("error");
      }
    });
    
  });



$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform_final">
<tr><th colspan="9">Digital Report [Ex: AC, Engine, Ignition, etc...]</th></tr>
  <tr>
    <td width="10%" align="right"><span class="form_text">Select Device</span>
	</td>
    <td width="13%" align="left">
        <select name="map_device_id" id="map_device_id" tabindex="1" style="width:100%;" onchange="getDeviceDetails(this)">
        <option value="0">Select Device</option>
        <?php 
        while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
        {
			$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_id]."_".$devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_id]."_".$devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php }} ?>	
        </select>
        <input type="hidden" name="txtVehicleName" id="txtVehicleName" />
        <input type="hidden" name="txtVehicleImei" id="txtVehicleImei" />
    </td>
     <td width="10%" align="right"><span class="form_text">Select Parameter</span>	 </td>
    <td width="13%" align="left">
        <select name="rdAlertBy" id="rdAlertBy" tabindex="3" style="width:100%">
        	<option value="0">Select Parameter</option>
        </select>
    </td>
    <td width="18%" align="right"><span class="form_text">From&nbsp;</span>
    <input type="text" name="from_date" id="from_date" readonly="true" tabindex="2" size="12" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:30%;"/>&nbsp;
    <span><input type="text" name="time3" readonly="true" id="time3" size="7" tabindex="3" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></span>
    </td>
    <td width="18%" align="right"><span class="form_text">To&nbsp;</span>
    <input type="text" name="to_date" id="to_date" size="12" style="width:30%;" tabindex="4" readonly="true" value="<?php if(isset($_POST[to_date])) echo $_POST[to_date]; else echo date("d-m-Y"); ?>" />&nbsp;
    <span><input type="text" name="time4" readonly="true" id="time4" size="7" tabindex="5" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></span>
    </td>
    <td width="12%" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=digitalReport';" tabindex="7" /> 
    </td>
  </tr>
  
</table>
</form>
</div>
<div id="popup_div" style=" display:block; border:0px;" >

</div>	
	
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{ 
//print_r($_POST);
$sdate = $_POST[from_date];
$edate = $_POST[to_date];

$splitPort = explode("_",$_POST[rdAlertBy]);

$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
$strtTime = (($strtTime[0] * 60) + $strtTime[1]);

$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
$endTime = (($endTime[0] * 60) + $endTime[1]);

//exit;
if($_POST[from_date] == $_POST[to_date])
{
	$data =  gpspathFunAll($_POST[from_date],$_POST[txtVehicleImei]);
	$res7 = getACReport($data,$strtTime,$endTime,"[".$splitPort[1]."=1]");
	
	if($res7)
	$onArr = $res7;		
	
	$res8 = getACReport($data,$strtTime,$endTime,"[".$splitPort[1]."=0]");
	if($res8)
	$offArr = $res8;
	//print_r($offArr);
}
else
{
	$z = GetDays($sdate, $edate);
	for($y=0; $y<count($z); $y++)
	{ 
		if($y == 0) 
		{
			$data =  gpspathFunAll($z[$y],$_POST[txtVehicleImei]);
			$res1 = getACReport($data,$strtTime,1439,"[".$splitPort[1]."=1]");	
			if($res1) $onArr[] = $res1;
			
			$res2 = getACReport($data,$strtTime,1439,"[".$splitPort[1]."=0]");
			if($res2) $offArr[] = $res2;
		}
		elseif($y == count($z)-1) 
		{
			$data =  gpspathFunAll($z[$y],$_POST[txtVehicleImei]);
			$res3 = getACReport($data,0,$endTime,"[".$splitPort[1]."=1]");		;
			if($res3) $onArr[] = $res3;
			
			$res4 = getACReport($data,0,$endTime,"[".$splitPort[1]."=0]");
			if($res4) $offArr[] = $res4;

		}
		elseif($y < count($z)-1) 
		{
			$data =  gpspathFunAll($z[$y],$_POST[txtVehicleImei]);
			$res5 = getACReport($data,0,1439,"[".$splitPort[1]."=1]");
			if($res5) $onArr[] = $res5;
			
			$res6 = getACReport($data,0,1439,"[".$splitPort[1]."=0]");
			if($res6) $offArr[] = $res6;
		}
	}
	
	if(count($onArr))
	$onArr = implode("@",$onArr);
	
	if(count($offArr))
	$offArr = implode("@",$offArr);
}
?>
<div style="float:left;" class="info_port"><?php echo $splitPort[0];?> On Details</div>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="onTable">      
  <thead>
    <tr>
    	<th width="4%">#</th>
        <th width="15%">Date (dd/mm/yy)</th>
        <th width="25%">Device Name</th> 
		<th width="25%">From & To (Time)</th>
        <th width="17%">Time Differece in <br/>(Hours:Minutes:Seconds)</th>
        <th width="10%"><?php echo $splitPort[0];?> Status</th>
       </tr>
   </thead>
   <tbody>
<?php
	if(count($onArr) > 0)
	{
		$onArr = explode("@",$onArr);
		for($x=0; $x<count($onArr); $x++)
		{
            $splitData = explode("#",$onArr[$x]);
			//print_r($splitData); echo "<br>";

		 ?>
			 <tr <?php if($x % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
			   <td valign="top"><?php echo $x+1; ?></td>
			   <td valign="top"><?php echo date('d-m-Y',strtotime($splitData[0])); ?></td>
			   <td valign="top"><?php echo $_POST[txtVehicleName]; ?></td>
			   <td valign="top"><?php echo $splitData[1]." - ".$splitData[2]; ?></td>
			   <td valign="top"><?php echo $splitData[3]; ?></td>
			   <td valign="top"><?php echo "On"; ?></td>
             </tr>
		 <?php 
		//exit;
		}
	}
?>
</tbody>
</table>
<div style="float:left;" class="info_port"><?php echo $splitPort[0];?> Off Details</div>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="offTable">      
  <thead>
    <tr>
    	<th width="4%">#</th>
        <th width="15%">Date (dd/mm/yy)</th>
        <th width="25%">Device Name</th> 
		<th width="25%">From & To (Time)</th>
        <th width="17%">Time Differece in <br/>(Hours:Minutes:Seconds)</th>
        <th width="10%"><?php echo $splitPort[0];?> Status</th>
       </tr>
   </thead>
   <tbody>
<?php
//print_r($offArr);
	if(count($offArr) > 0)
	{
		$offArr = explode("@",$offArr);
		for($x=0; $x<count($offArr); $x++)
		{
            $splitData = explode("#",$offArr[$x]);
			//print_r($splitData); echo "<br>";

		 ?>
			 <tr <?php if($x % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
			   <td valign="top"><?php echo $x+1; ?></td>
			   <td valign="top"><?php echo date('d-m-Y',strtotime($splitData[0])); ?></td>
			   <td valign="top"><?php echo $_POST[txtVehicleName]; ?></td>
			   <td valign="top"><?php echo $splitData[1]." - ".$splitData[2]; ?></td>
			   <td valign="top"><?php echo $splitData[3]; ?></td>
			   <td valign="top"><?php echo "Off"; ?></td>
             </tr>
		 <?php 
		//exit;
		}
	}
?>
</tbody>
</table>	
<?php }?> 
